package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.yuce.YuceMainDao;
import jsyf.oa.facade.system.SystemFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class SystemService implements SystemFacade {

    //公司dao
    @Autowired
    private CompanyDao companyDao;

    //部门dao
    @Autowired
    private DepartDao departDao;

    //组织dao
    @Autowired
    private RoleDao roleDao;

    //人员dao
    @Autowired
    private UserDao userDao;

    //区域dao
    private RegionDao regionDao;

    @Autowired
    private YuceMainDao yuceMainDao;

    @Override
    public JSONObject getUserViewBySqlWhere(JSONObject jsonParam, Integer requestPage, Integer pageSize) {
        JSONObject obj_result = new JSONObject();
        JSONObject obj_sendData = new JSONObject();
        String departId = jsonParam.getString("departId");
        String companyId = jsonParam.getString("companyId");
        String userId = jsonParam.getString("userId");
        String key = jsonParam.getString("key");
        String roleId = jsonParam.getString("roleId");
        //查询公司
        List<JSONObject> listCompanys = userDao.getViewJSONListByCondition(" AND jobState!=1 AND id = ? ", new Object[]{userId});
        List<String> listCompanyIds = new ArrayList<>();
        for (int i = 0; i < listCompanys.size(); i++) {
            String companyStr = listCompanys.get(i).getString("companyId");
            listCompanyIds.add(companyStr);
            companyDao.getChildrenIds(companyStr, listCompanyIds);
        }
        String companyIds = "";
        for (int i = 0; i < listCompanyIds.size(); i++) {
            companyIds += "'" + listCompanyIds.get(i) + "',";
        }
        if (companyIds.length() > 0) {
            companyIds = companyIds.substring(0, companyIds.length() - 1);
        }
        //查询部门
        List<JSONObject> listDeparts = departDao.getJSONListByCondition(" AND DEL_FLAG = '0' AND ID =" + "'" + departId + "' ", new Object[]{});
        List<String> listDepartIds = new ArrayList<>();
        for (int i = 0; i < listDeparts.size(); i++) {
            String departStr = listDeparts.get(i).getString("id");
            listDepartIds.add(departStr);
            departDao.getChildrenIds(departStr, listDepartIds);
        }
        String departIds = "";
        for (int i = 0; i < listDepartIds.size(); i++) {
            departIds += "'" + listDepartIds.get(i) + "',";
        }
        if (departIds.length() > 0) {
            departIds = departIds.substring(0, departIds.length() - 1);
        }
        //查询用户
        StringBuilder condition = new StringBuilder();
        List<Object> sqlArgs = new ArrayList<Object>();
        condition.append(" and main = 1 ");
        //公司参数
        if (!StringUtils.isBlank(companyIds)) {
            condition.append(" and companyId IN(" + companyIds + ")");
        }
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" and companyId = '" + companyId + "' ");
        }
        //部门参数
        if (!StringUtils.isBlank(departIds)) {
            condition.append(" and departId IN(" + departIds + ")");
        }
        //职位参数
        if (!StringUtils.isBlank(roleId)) {
            condition.append(" and roleId= ?");
            sqlArgs.add(roleId);
        }
        //模糊查询参数
        if (!StringUtils.isBlank(key)) {
            condition.append(" and (name LIKE ? or tel LIKE ? or spell LIKE ? or F_GETPY(name) LIKE ?)");
            sqlArgs.add("%" + key + "%");
            sqlArgs.add("%" + key + "%");
            sqlArgs.add("%" + key + "%");
            sqlArgs.add("%" + key + "%");
        }
        List<JSONObject> listUser = userDao.getViewListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        //查询出总数
        int recordCount = userDao.getViewPageCount(condition.toString(), sqlArgs.toArray());
        int recordSize = Integer.valueOf(pageSize).intValue();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % recordSize == 0 ? recordCount / recordSize : (recordCount / recordSize) + 1;
        //子对象
        obj_sendData.put("recordCount", recordCount);
        obj_sendData.put("pageCount", pageCount);
        obj_sendData.put("requestPage", 1);
        obj_result.put("pager", obj_sendData);
        // 子数组对象
        obj_result.put("records", listUser);
        return obj_result;
    }

    @Override
    public List<JSONObject> getCDUAll() {
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        List<JSONObject> listDeparts = new ArrayList<>();
        List<JSONObject> listUser = new ArrayList<>();
        //查询所有公司
        listCompanies = getCompanyByAll();
        //查询所有部门
        listDeparts = getDepartByAll();
        //查询所有人员
        listUser = getUserByAll();
        listResult = getJsonObjectTree(listResult, null, listDeparts, listCompanies);
        //添加人员节点
        for (int i = 0; i < listUser.size(); i++) {
            JSONObject objNode = listUser.get(i);
            String user2Id = objNode.getString("id");
            String departId = objNode.getString("departId");
            objNode.put("id", user2Id);
            objNode.put("pId", departId);
            objNode.put("name", objNode.getString("name"));
            objNode.put("type", "user");
            objNode.put("dataId", user2Id);
            listResult.add(objNode);
        }
        return listResult;
    }

    @Override
    public List<JSONObject> getCompanyTree(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyIds = jsonParam.getString("companyId");
        String userId = jsonParam.getString("userId");
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        //查询所有公司
        if (companyIds.equalsIgnoreCase("201712161613432EAF27DBCCB7D0E6CA")) {
            listCompanies = getCompanyByGGXQ(companyIds);
        } else {
            listCompanies = getCompanyByParentId(companyIds);
        }
        List<JSONObject> OtherCompanyies = companyDao.getPartCompanyId(userId, companyIds);
        if (OtherCompanyies.size() > 0) {
            for (JSONObject object : OtherCompanyies) {
                listCompanies.add(object);
            }
        }
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objNode = listCompanies.get(i);
            String companyId = objNode.getString("id");
            objNode.put("id", companyId);
            String parentId = objNode.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objNode.put("pId", "0");
                    objNode.put("open", true);
                } else {
                    objNode.put("pId", parentId);
                    objNode.put("open", false);
                }
            } else {
                objNode.put("pId", "0");
                objNode.put("open", true);
            }
            objNode.put("name", objNode.getString("name"));
            objNode.put("type", "company");
            objNode.put("dataId", companyId);
            objNode.put("companyId", companyId);
            listResult.add(objNode);
        }

        return listResult;
    }


    @Override
    public List<JSONObject> getOrgTreeNodesByUserId(String userId) {
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        List<JSONObject> listDeparts = new ArrayList<>();
        List<JSONObject> listRoles = new ArrayList<>();
        if (userDao.isSuperUser(userId)) {
            //查询所有公司
            listCompanies = getCompanyByAll();
            //查询所有部门
            listDeparts = getDepartByAll();
            //查询所有职位
            listRoles = getRoleByAll();
        } else {
            List<JSONObject> listUsers = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{userId});
            List<String> listCompanyIds = new ArrayList<>();

            for (int i = 0; i < listUsers.size(); i++) {
                String companyId = listUsers.get(i).getString("companyId");
                listCompanyIds.add(companyId);
                companyDao.getChildrenIds(companyId, listCompanyIds);
            }
            String companyIds = "";
            for (int i = 0; i < listCompanyIds.size(); i++) {
                companyIds += "'" + listCompanyIds.get(i) + "',";
            }
            companyIds = companyIds.substring(0, companyIds.length() - 1);
            listCompanies = companyDao.getJSONListByCondition(" AND DEL_FLAG = '0' AND ID IN(" + companyIds + ") ORDER BY SORT_NO ", new Object[]{});
            listDeparts = departDao.getJSONListByCondition(" AND DEL_FLAG = '0' and COMPANY_ID IN(" + companyIds + ") ORDER BY SORT_NO ", new Object[]{});
            String departIds = "";
            for (int i = 0; i < listDeparts.size(); i++) {
                departIds += "'" + listDeparts.get(i).getString("id") + "',";
            }
            departIds = departIds.substring(0, departIds.length() - 1);
            listRoles = roleDao.getViewJSONListByCondition(" AND delFlag = 0 and departId IN(" + departIds + ") ORDER BY sortNo ", new Object[]{});

        }

        listResult = getJsonObjectTree(listResult, listRoles, listDeparts, listCompanies);


        return listResult;

    }

    private List<JSONObject> getJsonObjectTree(List<JSONObject> listResult, List<JSONObject> listRoles, List<JSONObject> listDeparts, List<JSONObject> listCompanies) {
        JSONObject objRoot = new JSONObject();
        objRoot.put("id", "0");
        objRoot.put("name", "组织机构");
        objRoot.put("type", "root");
        objRoot.put("dataId", "0");
        objRoot.put("open", true);
        objRoot.put("isParent", true);
        listResult.add(objRoot);
        //添加职位节点
        if (listRoles != null && listRoles.size() > 0) {
            for (int i = 0; i < listRoles.size(); i++) {
                JSONObject objNode = listRoles.get(i);
                String roleId = objNode.getString("id");
                String departId = objNode.getString("departId");
                objNode.put("id", roleId);
                objNode.put("pId", departId);
                objNode.put("name", objNode.getString("roleName"));
                objNode.put("type", "role");
                objNode.put("dataId", roleId);
                objNode.put("targetNumber", objNode.getString("targetNumber"));
                listResult.add(objNode);
            }
        }
        //添加部门节点
        for (int i = 0; i < listDeparts.size(); i++) {
            JSONObject objNode = listDeparts.get(i);
            String departId = objNode.getString("id");
            String parentId = objNode.getString("parentId");
            String companyId = objNode.getString("companyId");

            objNode.put("id", departId);
            if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                objNode.put("pId", companyId);
            } else {
                objNode.put("pId", parentId);
            }
            objNode.put("name", objNode.getString("name"));
            objNode.put("type", "depart");
            objNode.put("dataId", departId);
            objNode.put("isParent", true);
            objNode.put("companyId", companyId);
            listResult.add(objNode);
        }

        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objNode = listCompanies.get(i);
            String companyId = objNode.getString("id");
            objNode.put("id", companyId);
            String parentId = objNode.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objNode.put("pId", "0");
                    objNode.put("open", true);
                } else {
                    objNode.put("pId", parentId);
                    objNode.put("open", false);
                }
            } else {
                objNode.put("pId", "0");
                objNode.put("open", true);
            }
            objNode.put("name", objNode.getString("name"));
            objNode.put("type", "company");
            objNode.put("dataId", companyId);
            objNode.put("companyId", companyId);
            objNode.put("isParent", true);
            listResult.add(objNode);
        }

        return listResult;
    }


    public List<JSONObject> getCompanyByAll() {
        return companyDao.getJSONListByCondition(" AND DEL_FLAG = '0' ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getCompanyByGGXQ(String companyId) {
        return companyDao.getJSONListByCondition(" AND (PARENT_ID='" + companyId + "' OR ID='" + companyId + "') AND ID !='2017121617484A2796D8F52B6B558B94' AND DEL_FLAG = '0' ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getCompanyByParentId(String companyId) {
        return companyDao.getJSONListByCondition(" AND (ID='" + companyId + "' OR ID='201712161613432EAF27DBCCB7D0E6CA') AND ID !='2017121617484A2796D8F52B6B558B94' AND DEL_FLAG = '0' ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getDepartByAll() {
        return departDao.getJSONListByCondition(" AND DEL_FLAG = '0' ORDER BY SORT_NO ", new Object[]{});
    }

    public List<JSONObject> getRoleByAll() {
        return roleDao.getViewJSONListByCondition(" and delFlag = 0 ORDER BY sortNo ", new Object[]{});
    }

    public List<JSONObject> getUserByAll() {
        //查询人员
        return userDao.getViewJSONListByCondition(" AND main=1 AND jobState!=1 ORDER BY companySortNo,departSortNo,roleSortNo,userSortNo ", new Object[]{});
    }

    //获取服务器时间
    public String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(userDao.getCurrentTime());
        return dateString;
    }

    @Override
    public List<JSONObject> getOrgTreeByUserId(String jsonData) {
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        List<JSONObject> listDeparts = new ArrayList<>();
        List<JSONObject> listUsers = new ArrayList<>();
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String currentUserId = jsonParam.getString("userId");
        List<JSONObject> users = userDao.getViewJSONListByCondition(" and id = ?", new Object[]{currentUserId});
        List<String> listCompanyIds = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            String companyId = users.get(i).getString("companyId");
            listCompanyIds.add(companyId);
            companyDao.getChildrenIds(companyId, listCompanyIds);
        }
        String companyIds = "";
        for (int i = 0; i < listCompanyIds.size(); i++) {
            companyIds += "'" + listCompanyIds.get(i) + "',";
        }
        companyIds = companyIds.substring(0, companyIds.length() - 1);
        listCompanies = companyDao.getJSONListByCondition(" AND DEL_FLAG = 0 AND ID IN(" + companyIds + ") ORDER BY SORT_NO ", new Object[]{});
        listDeparts = departDao.getJSONListByCondition(" AND DEL_FLAG = 0  AND COMPANY_ID IN(" + companyIds + ")" +
                " AND  (NAME LIKE '%区%' OR NAME='销售部') ORDER BY SORT_NO ", new Object[]{});
        String departIds = "";
        for (int i = 0; i < listDeparts.size(); i++) {
            departIds += "'" + listDeparts.get(i).getString("id") + "',";
        }
        departIds = departIds.substring(0, departIds.length() - 1);
        listUsers = userDao.getViewJSONListByCondition(" AND main=1 AND jobState!=1 " +
                "AND roleName='区域经理'  AND departId IN(" + departIds + ") " +
                "ORDER BY companySortNo,departSortNo,roleSortNo,userSortNo ", new Object[]{});


        //查询人员
        for (int j = 0; j < listUsers.size(); j++) {
            JSONObject objUser = listUsers.get(j);
            objUser.put("pId", objUser.getString("departId"));
            objUser.put("type", "user");
            listResult.add(objUser);
        }
        //添加部门节点
        for (int i = 0; i < listDeparts.size(); i++) {
            JSONObject objDepart = listDeparts.get(i);
            String departId = objDepart.getString("id");
            String parentId = objDepart.getString("parentId");
            String companyId = objDepart.getString("companyId");
            if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                objDepart.put("pId", companyId);
            } else {
                objDepart.put("pId", parentId);
            }
            objDepart.put("type", "depart");
            objDepart.put("dataId", departId);
            objDepart.put("isParent", true);
            listResult.add(objDepart);
        }
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objCompany = listCompanies.get(i);//id,name,sortNo,
            String parentId = objCompany.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (com.alibaba.dubbo.common.utils.StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objCompany.put("pId", "0");
                    objCompany.put("open", true);
                } else {
                    objCompany.put("pId", parentId);
                    objCompany.put("open", false);
                }
            } else {
                objCompany.put("pId", "0");
                objCompany.put("open", true);
            }
            objCompany.put("type", "company");
            objCompany.put("isParent", true);
            listResult.add(objCompany);
        }

        return listResult;
    }

    @Override
    public List<JSONObject> getCompanyTreeForXSTZ(String jsonData) {
        JSONObject jsonParam = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyIds = jsonParam.getString("companyId");
        List<JSONObject> listResult = new ArrayList<>();
        List<JSONObject> listCompanies = new ArrayList<>();
        //查询所有公司
        if (companyIds.equalsIgnoreCase("201712161613432EAF27DBCCB7D0E6CA")) {
            listCompanies = getCompanyByGGXQ(companyIds);
        } else {
            listCompanies = getCompanyByParentId(companyIds);
        }
        //添加公司节点
        for (int i = 0; i < listCompanies.size(); i++) {
            JSONObject objNode = listCompanies.get(i);
            String companyId = objNode.getString("id");
            objNode.put("id", companyId);
            String parentId = objNode.getString("parentId");
            if ("0".equals(listCompanies.get(0).getString("parentId"))) {
                if (StringUtils.isEmpty(parentId) || ("0").equals(parentId)) {
                    objNode.put("pId", "0");
                    objNode.put("open", true);
                } else {
                    objNode.put("pId", parentId);
                    objNode.put("open", false);
                }
            } else {
                objNode.put("pId", "0");
                objNode.put("open", true);
            }
            objNode.put("name", objNode.getString("name"));
            objNode.put("type", "company");
            objNode.put("dataId", companyId);
            objNode.put("companyId", companyId);
            listResult.add(objNode);
        }
        //根节点root
        JSONObject objRoot = new JSONObject();
        objRoot.put("id", "0");
        objRoot.put("name", "组织机构");
        objRoot.put("type", "root");
        objRoot.put("open", true);
        objRoot.put("isParent", true);
        listResult.add(objRoot);

        return listResult;
    }
}
